<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8" />
      <title>Using deferred.progress() version 1 - jQuery in Action, 3rd edition</title>
      <link rel="stylesheet" href="../css/main.css"/>
      <style>
         .bar,
         .inner-bar
         {
            height: 50px;
            border-radius: 3px;
         }

         .bar
         {
            position: relative;
            border: 1px solid #000000;
            background-color: #CCCCCC;
         }

         .inner-bar
         {
            width: 0;
            background-color: #F72F39;
         }

         .progress
         {
            position: absolute;
            font-size: 30px;
            width: 100%;
            text-align: center;
            top: 10px;
         }

         button
         {
            margin-top: 15px;
         }
      </style>
   </head>
   <body>
      <div class="bar">
         <div class="inner-bar"></div>
         <span class="progress">0%</span>
      </div>

      <button id="run-button">Run animation</button>

      <script src="../js/jquery-1.11.3.min.js"></script>
      <script>
         function animate(milliseconds) {
            var $innerBar = $('.inner-bar').width(0);
            var $barWidth = $('.bar').width();
            var step = $barWidth / 100;

            var deferred = $.Deferred().progress(function (value) {
               $('.progress').text(Math.floor(value) + '%');
            });

            var idInterval = setInterval(
               function () {
                  // Can't use width() to retrieve the width because
                  // of issue #1724 (https://github.com/jquery/jquery/issues/1724)
                  var nextWidth = parseFloat($innerBar.get(0).style.width) + step;
                  deferred.notify(nextWidth * 100 / $barWidth);
                  $innerBar.width(nextWidth);
                  if (nextWidth >= $barWidth) {
                     deferred.resolve();
                     clearInterval(idInterval);
                  }
               },
               milliseconds / 100
            );

         }

         $('#run-button').click(function() {
            animate(1000);
         });
      </script>
   </body>
</html>